package com.cupk.carManageMaster.Interceptor;

import com.cupk.carManageMaster.common.domain.ResponseBase;
import com.cupk.carManageMaster.common.domain.TokenInfo;
import com.cupk.carManageMaster.util.JsonUtils;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
 * 名称UserInterceptor
 * 描述UserInterceptor
 *
 * @version 1.0
 * @author:wanghao
 * @datatime:2023,06,01,15,59
 */
public class UserInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
        if (true) {
            return true;
        }
        Jedis jedis = new Jedis("r-bp1fckprlkd7o7t322pd.redis.rds.aliyuncs.com", 6379);  //指定Redis服务Host和port
        jedis.auth("Wh314159*"); //如果Redis服务连接需要密码，制定密码
        // 检查用户传递的 token是否合法
        TokenInfo tokenInfo = this.getUserToKen(request);
        String token = jedis.get(tokenInfo.getAdminId());
        jedis.close();
        if (StringUtils.isBlank(tokenInfo.getAdminId()) && StringUtils.isBlank(tokenInfo.getToken())) {
            // 返回登录
            System.out.println("没有传入对应的身份信息，返回登录");
            return false;
        }
        try {
            System.out.println(tokenInfo.getAdminId());
            System.out.println(tokenInfo.getToken());
            if (token != null && token.equals(tokenInfo.getToken())) {
                System.out.println("校验成功");
                return true;
            } else {
                System.out.println("校验失败，返回登录");
                return false;
            }
        } catch (Exception e) {
            System.out.println("校验失败,对应的信息匹配错误，返回登录");
            return false;
        }

    }

    /**
     * 在cookie中获取用户传递的token
     */
    private TokenInfo getUserToKen(HttpServletRequest request) {
        TokenInfo info = new TokenInfo();
        String adminId = request.getHeader("adminId");
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(adminId) && StringUtils.isNotBlank(token)) {
            info.setAdminId(adminId);
            info.setToken(token);
        }
        return info;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv)
            throws Exception {
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行 （主要是用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex)
            throws Exception {
    }

    public void returnErrorResponse(HttpServletResponse response, ResponseBase result)
            throws IOException, UnsupportedEncodingException {
        OutputStream out = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
